<template>
  <g-form-wrap v-loading.fullscreen.lock="pageLoading" :title="title" :on-save-btn-click="onSaveBtnClick">
    <el-form
      ref="ruleForm"
      :model="formData"
      :rules="formRules"
      label-position="left"
      label-width="140px"
      inline
    >
      <div class="w-full">
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="菜单中文名称：" prop="nameCn">
              <el-input
                v-model="formData.nameCn"
                placeholder="请输入菜单中文名称"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单英文名称：" prop="nameEn">
              <el-input
                v-model="formData.nameEn"
                placeholder="请输入菜单英文名称"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <!-- <el-col :span="12">
            <el-form-item label="父级菜单" prop="pid">
              <g-select
                v-model="formData.pid"
                placeholder="请选择父级菜单"
                class="edit-item"
                :options="options"
                :filterable="true"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <g-select
                v-model="formData.type"
                placeholder="请选择菜单类型"
                class="edit-item"
                disabled
                :options="[{'id': 1, 'name': ' 菜单'}, {'id': 2, 'name': '权限'}]"
                :filterable="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路径：" prop="path">
              <el-input
                v-model="formData.path"
                placeholder="请输入路径"
                class="edit-item"
                clearable
                @change="() => {
                  formData.privilege = kebabCase(trimStart(formData.path, '/'))
                }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="权限标记：" prop="privilege">
              <el-input
                v-model="formData.privilege"
                class="edit-item"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row type="flex" v-if="isEditing">
          <el-col :span="12">
            <el-form-item label="子路径：" prop="children">
              <g-tree
                :tree-data="subMenuData"
                :is-operator="true"
                @show-opt-dialog-func="showOptDialogFunc"
              />
            </el-form-item>
          </el-col>
        </el-row> -->
      </div>
    </el-form>
    <div v-if="isEditing">
      <el-button
        :icon="Plus"
        plain
        type="primary"
        @click="addOrEditSubMenuFunc"
      >
        添加菜单/权限节点
      </el-button>
      <el-table
        v-if="isEditing"
        :data="subMenuData"
        style="width: 100%; margin-bottom: 20px; margin-top: 10px"
        row-key="id"
        border
        default-expand-all
        :row-class-name="getRowClassFunc"
      >
        <el-table-column prop="menuId" label="ID" width="100" />
        <el-table-column prop="nameCn" label="菜单中文名称" />
        <el-table-column prop="nameEn" label="菜单英文名称" />
        <el-table-column prop="privilege" label="权限标记" />
        <el-table-column prop="pnameCn" label="父级菜单" />
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="type" label="菜单类型" width="100">
          <template #default="scope">
            <span v-if="scope.row.type === 1">菜单</span>
            <span v-if="scope.row.type === 2">权限</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="菜单状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" class="ml-2" type="success">有效</el-tag>
            <el-tag v-else class="ml-2" type="danger">无效</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              link
              :disabled="scope.row.status == 1 ? false : true"
              @click="addOrEditSubMenuFunc(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status == 1 "
              link
              size="small"
              type="danger"
              @click="removeSubMenuFunc(scope.row.menuId, 0)"
            >
              删除
            </el-button>
            <el-button
              v-else
              link
              size="small"
              type="success"
              @click="removeSubMenuFunc(scope.row.menuId, 1)"
            >
              恢复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </g-form-wrap>

  <g-dialog
    v-model:dialog-visible="showOptDialog"
    :title="(subMenuId ? '编辑' : '添加') + `菜单/权限节点`"
    :click-sure-btn="saveSubFormDataFunc"
    width="600"
  >
    <el-form
      ref="subRuleForm"
      :model="subFormData"
      :rules="subFormRules"
      label-position="left"
      label-width="140px"
      inline
    >
      <div class="w-full">
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="菜单中文名称：" prop="nameCn">
              <el-input
                v-model="subFormData.nameCn"
                placeholder="请输入菜单中文名称"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="菜单英文名称：" prop="nameEn">
              <el-input
                v-model="subFormData.nameEn"
                placeholder="请输入菜单英文名称"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="父级菜单" prop="pid">
              <g-select
                v-model="subFormData.pid"
                placeholder="请选择父级菜单"
                class="edit-item"
                :options="subOptions"
                :filterable="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="类型" prop="type">
              <g-select
                v-model="subFormData.type"
                placeholder="请选择菜单类型"
                class="edit-item"
                :options="[{'id': 1, 'name': ' 菜单'}, {'id': 2, 'name': '权限'}]"
                :filterable="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="路径：" prop="path">
              <el-input
                v-model="subFormData.path"
                placeholder="请输入路径"
                class="edit-item"
                clearable
                @change="() => {
                  subFormData.privilege = kebabCase(trimStart(subFormData.path, '/'))
                }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="24">
            <el-form-item label="权限标记：" prop="privilege">
              <el-input
                v-model="subFormData.privilege"
                class="edit-item"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </g-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Loading } from '@/components/Dialog/types'
import { useRoute, useRouter } from 'vue-router'
import elv from '@/utils/elValidation'
import { getBackMenuListApi, getBackMenuByIdApi, addBackMenuApi, updateBackMenuApi } from '@/api/system'
import { Page } from '@/types/storeModule'
import { assign, cloneDeep, omit, kebabCase, trimStart, size, fill } from 'lodash-es'

let showOptDialog = ref(false)
let pageLoading = ref<boolean>(true)
const route = useRoute()
const router = useRouter()
const isEditing = ref(false)
const ruleForm = ref<FormInstance>()
let options = ref<any>([])
let formData = ref(<
  {
    menuId: string | number
    nameCn: string
    nameEn: string
    pid: string | number
    path: string
    privilege: string
    type: number
  }
>{
  menuId: 0,
  nameCn: '',
  nameEn: '',
  pid: '',
  path: '/',
  privilege: '',
  type: 1
})
formData.value.privilege = kebabCase(trimStart(formData.value.path, '/'))
const formRules = reactive<FormRules>({
  nameCn: [{ required: true, message: '请输入中文名称', trigger: 'change' }],
  nameEn: [{ required: true, message: '请输入英文名称', trigger: 'change' }],
  path: [{ required: true, message: '请输入路径', trigger: 'change' }]
})
const id = route.query.id as string | number
const title = route.meta.title as string
isEditing.value = id > 0 ? true : false
let subMenuData = ref<treeOption>([])
let subOptions = ref<any>([])
// 编辑时
let getBackMenuByIdFunc
if (isEditing.value) {
  getBackMenuByIdFunc = async () => {
    const data = await getBackMenuByIdApi({ id: id })
    // console.log('getBackMenuByIdApi---', data);
    if (data.pid == 0) data.pid = ''
    formData.value = cloneDeep(omit(data, ['History', 'history', 'repeatKeys']))
    subMenuData.value = cloneDeep(data.children)
    // console.log('subMenuData---', subMenuData.value);
    getBackMenuListFunc()
    pageLoading.value = false
  }
  getBackMenuByIdFunc()
} else {
  pageLoading.value = false
}
// 初始化父级菜单
const getBackMenuListFunc = async () => {
  try {
    const page = reactive<Page>({
      currentPage: 1,
      pageSize: 1000
    })
    const data = await getBackMenuListApi({ page: page })
    if (data.result) {
      const opList = data.result.map((item) => {
        return { id: item.menuId, name: item.nameCn }
      })
      options.value = cloneDeep(opList)
    }
    // console.log('options==.value=', options);
  } catch (err) {
    pageLoading.value = false
  }
}

// 保存提交
const onSaveBtnClick = (loading: Loading) => {
  ruleForm.value?.validate((valid) => {
    if (valid) {
      loading(true)
      if (isEditing.value) {
        // console.log('formData---update', formData);
        updateBackMenuApi(formData.value).then((res) => {
          // console.log('res---update', res);
          if(res*1 === 200)
            ElMessage.success('编辑成功')
        })
      } else {
        // console.log('formData---add', formData);
        addBackMenuApi(formData.value).then((res) => {
          // console.log('res---add', res);
          if(res*1 === 201)
            ElMessage.success('添加成功')
        })
      }
      setTimeout(() => {
        loading(false)
        router.back()
      }, 100)
    } else {
      return false
    }
  })
}

const subRuleForm = ref<FormInstance>()
let subFormData = ref(<
  {
    menuId: string | number
    nameCn: string
    nameEn: string
    pid: string | number
    path: string
    privilege: string
    type: number
  }
>{
  menuId: 0,
  nameCn: '',
  nameEn: '',
  pid: '',
  path: '/',
  privilege: '',
  type: 2
})
const subFormRules = reactive<FormRules>({
  nameCn: [{ required: true, message: '请输入中文名称', trigger: 'change' }],
  nameEn: [{ required: true, message: '请输入英文名称', trigger: 'change' }],
  path: [{ required: true, message: '请输入路径', trigger: 'change' }],
  pid: [{ required: true, message: '请输选择父级菜单', trigger: 'change' }]
})
let subMenuId = ref<string | number>('')
const addOrEditSubMenuFunc = (row) => {
  // console.log('row---', row);
  // console.log('id---', id);
  let retList = ref<any>([])
  // 初始化subOptions
  mergeList(retList, [formData.value])
  if(row.menuId){
    subFormData.value = cloneDeep(omit(row, ['History', 'history', 'repeatKeys']))
  }else{
    subFormData.value = {
      menuId: 0,
      nameCn: '',
      nameEn: '',
      pid: '',
      path: '/',
      privilege: '',
      type: 2
    }
  }
  subOptions.value = retList.value.map((item) => {
    return { id: item.menuId, name: item.nameCn }
  })
  showOptDialog.value = true
  subMenuId.value = row.menuId
}

const mergeList = (retList, list) => {
  list.forEach((item) => {
    retList.value.push(item)
    if(size(item.children) > 0){
      mergeList(retList, item.children)
    }
  })
}
const removeSubMenuFunc = (menuId, status) => {
  updateBackMenuApi({ menuId: menuId, status: status }).then((res) => {
    if(res * 1 === 200){
      ElMessage.success(status == 0 ? '删除成功' : '恢复成功')
      getBackMenuByIdFunc()
    }
  })
}
const saveSubFormDataFunc = async (loading: Loading) => {
  await subRuleForm.value?.validate((valid) => {
    if (valid) {
      loading(true)
      if (subMenuId.value) {
        console.log('subFormData---update', subFormData)
        updateBackMenuApi(subFormData.value).then((res) => {
          console.log('res---update', res)
          if(res*1 === 200)
            ElMessage.success('编辑成功')
        })
      } else {
        // console.log('subFormData---add', subFormData);
        addBackMenuApi(subFormData.value).then((res) => {
          console.log('res---add', res)
          if(res*1 === 201)
            ElMessage.success('添加成功')
        })
      }
      loading(false)
    } else {
      return false
    }
  })
  showOptDialog.value = false
  router.go(0)
}
const getRowClassFunc = (row,rowIndex) => {
  // console.log('row---', row);
  // 判断当前行是否有子数据
  if(row.row.children === null || row.row.children === undefined || row.row.children.length === 0){
    return 'row-hidden-expand-icon'
  }
}
</script>
<style lang="scss">
  .row-hidden-expand-icon{
    td{
      &:first-child{
        .el-icon{
            visibility: hidden;
        }
      }
      .el-table__expand-icon{
        pointer-events: none;
      }
    }
}
</style>
